package com.wang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wang.common.utils.PageUtils;
import com.wang.common.utils.Query;
import com.wang.gulimall.product.dao.CategoryDao;
import com.wang.gulimall.product.entity.CategoryEntity;
import com.wang.gulimall.product.service.CategoryBrandRelationService;
import com.wang.gulimall.product.service.CategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 组装商品菜单为父子类型的树形结构
     * @return
     */
    @Override
    public List<CategoryEntity> CategoryEnsWithTree() {
        //1获取所有的菜单列表
        List<CategoryEntity> resList = baseMapper.selectList(null);
        //2组装成父子树形结构

        //2.1先找到所有的一级菜单（一级菜单的parentCid为0）
        List<CategoryEntity> level1Meuns = resList.stream()
                //过滤器，只留下父级id为0的元素，
                .filter((categoryEntity) -> categoryEntity.getParentCid() == 0)
                //对每一个元素经行操作 给他添加子菜单
                .map((categoryEntity -> {
                    categoryEntity.setChildren(getChildrens(categoryEntity, resList));
                    return categoryEntity;
                }))
                //对这个数组按照sort排序
                .sorted((categoryEntity1, categoryEntity2) -> {
                    return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
                })
                //收集到数组中
                .collect(Collectors.toList());

        return level1Meuns;
    }

    //递归寻找所有的子菜单

    /**
     *
     * @param root：目标菜单
     * @param all：所有菜单
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrenList = all.stream()
                //过滤器，如果流里面的每个元素的ParentCid == 目标菜单的catid。说明这个元素是目标菜单的子菜单
                //也就是返回的这个childrenList就是目标元素的子菜单的合集
                .filter((categoryEntity) -> {
                    return categoryEntity.getParentCid() == root.getCatId();
                }).map(categoryEntity -> {
                    //递归找到子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }).sorted((categoryEntity1, categoryEntity2) -> {
                    return (categoryEntity1.getSort() == null ? 0 : categoryEntity1.getSort()) - (categoryEntity2.getSort() == null ? 0 : categoryEntity2.getSort());
                }).collect(Collectors.toList());

        return childrenList;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    //菜单删除
    @Override
    public void removeMenuByIds(List<Long> ids) {
        //todo 1，删除时需判断当前菜单是否被引用

        //删除菜单 实际开发中多使用逻辑删除
        baseMapper.deleteBatchIds(ids);

    }

    @Override
    public Long[] getCatelogIds(Long CatelogId) {
        ArrayList<Long> longs = new ArrayList<>();
        Long[] parentID = getParentID(CatelogId,longs);
        return parentID;
    }

    /**
     * 级联修改，修改菜单名字的时候需要修改其他表中的菜单名字，保持一致
     * @param category
     */
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        String categoryName = category.getName();
        if (StringUtils.isNotEmpty(categoryName)){
            categoryBrandRelationService.updateCategoryNameByCategoryId(category.getCatId(),categoryName);
        }
    }

    public Long[] getParentID(Long CatelogId,ArrayList<Long> longs){
        CategoryEntity categoryEntity = this.getById(CatelogId);
        Long parentCid = categoryEntity.getParentCid();
        longs.add(CatelogId);
        if (parentCid !=0){
            getParentID(parentCid,longs);
        }
        Collections.reverse(longs);
        return longs.toArray(new Long[longs.size()]);
    }

}